//
//  ProcessedSelectedViewController.m
//  BaishidaiShop
//
//  Created by mac book on 2019/1/23.
//  Copyright © 2019年 sy. All rights reserved.
//

#import "ProcessedSelectedViewController.h"

#import "NewOrderTableViewCell.h"
#import "FinishedOrderFooterView.h"
#import "FinishedOrderHeaderView.h"
#import "HandleOrderHeaderView.h"


#define  GoodsCell_H  60


@interface ProcessedSelectedViewController ()<HandleOrderHeaderDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UITableViewDelegate,UITableViewDataSource,HandleFooterCallDelegate>

@property(nonatomic,strong) UIView* headerView;
@property(nonatomic,strong) UIView* lineView;
@property(nonatomic,strong) UITableView* tableView;


@property(nonatomic,strong) Pager* page;
@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* finishedHeaderIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSString* footerIdentitifer;

@property (nonatomic, strong) NSArray *statusArray;

@property (nonatomic, strong) UIButton *statusBtn;
@property (nonatomic, strong) UIButton *startBtn;
@property (nonatomic, strong) UIButton *endBtn;


@property (nonatomic, strong) NSString *statusStr;
@property (nonatomic, strong) NSString *startStr;
@property (nonatomic, strong) NSString *endStr;

@end

@implementation ProcessedSelectedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"搜索";
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 60, 25);
    [rightButton setTitle:@"重置" forState:UIControlStateNormal];
    [rightButton setTitleColor:getColor(mainColor) forState:UIControlStateNormal];
    rightButton.titleLabel.font = kFontNameSize(15);
    [rightButton addTarget:self action:@selector(rightButton) forControlEvents:UIControlEventTouchUpInside];
    //添加到导航条
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    

    self.cellIdentifier = @"OrderCell";
    self.finishedHeaderIdentifier = @"FinishedOrderHeader";
    self.headerIdentifier = @"HandleOrderHeader";
    self.footerIdentitifer = @"FinishedOrderFooter";
    self.statusStr = self.startStr = self.endStr = @"";
    
    [self getSelectedData];
    
}

-(void)rightButton{
    
    self.statusStr = self.startStr = self.endStr = @"";
    [self.statusBtn setTitle:@"订单状态" forState:UIControlStateNormal];
    [self buttonEdgeInsets:self.statusBtn];
    
    [self.startBtn setTitle:@"开始时间" forState:UIControlStateNormal];
    [self buttonEdgeInsets:self.startBtn];
    
    [self.endBtn setTitle:@"结束时间" forState:UIControlStateNormal];
    [self buttonEdgeInsets:self.endBtn];
    
    self.page.pageIndex = 1;
    [self.tableView.mj_header beginRefreshing];

}

- (void)getSelectedData{
    
    [self showHUD];
    NSDictionary* arg = @{
                          @"ince":@"get_order_status_list",
                          @"sid":[UserHandle shareInstance].userId
                          };
    
    
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"data = %@",data);
        
        
        NSInteger flag = [[data objectForKey:@"ret"]integerValue];
        if(flag == 200){
            
            [self hidHUD];
            NSArray *dataArray = data[@"data"];
            self.statusArray = [OrderModel mj_objectArrayWithKeyValuesArray:dataArray];
            
            [self creatSubViews];
            
            [self refreshDataSource];
            
        }else{
            [self hidHUD:[data objectForKey:@"msg"]];
        }
        
    } failure:^(NSError *error) {
        [self hidHUD:@"网络异常"];
    }];
    
    
    
    
}
#pragma mark - creatSubViews
-(void)creatSubViews{
    
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.lineView];
    [self.view addSubview:self.tableView];

    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(40);
    }];
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(0.8);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.lineView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    float button_w = SCREEN_WIDTH/3;
    float button_h = 40;
    
    self.statusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.statusBtn.frame = CGRectMake(0, 0, button_w, button_h);
    [self setUpButton:self.statusBtn withText:@"订单状态"];
    
 
    
    self.startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.startBtn.frame = CGRectMake(CGRectGetMaxX(self.statusBtn.frame), 0, button_w, button_h);
    [self setUpButton:self.startBtn withText:@"开始时间"];
    
   
    
    self.endBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.endBtn.frame = CGRectMake(CGRectGetMaxX(self.startBtn.frame), 0,  button_w, button_h);
    [self setUpButton:self.endBtn withText:@"结束时间"];
    

    
}


#pragma mark - Data source
-(void)getData{
    
    NSDictionary* arg = @{
                          @"ince":@"get_order_list",
                          @"sid":[UserHandle shareInstance].userId,
                          @"page":[WMHelper integerConvertToString:self.page.pageIndex],
                          @"status":self.statusStr,
                          @"starttime":self.startStr,
                          @"endtime":self.endStr
                          };
    
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
//        NSLog(@"data = %@",data);
        
        if(self.page.pageIndex == 1){
            [self.page.arrayData removeAllObjects];
        }
        NSInteger flag = [[data objectForKey:@"ret"]integerValue];
        if(flag == 200){
            self.page.recordCount = [[data objectForKey:@"total"] integerValue];
            self.page.pageSize = [[data objectForKey:@"number"]integerValue];
            NSInteger empty = self.page.recordCount % self.page.pageSize;
            if(empty == 0){
                self.page.pageCount = self.page.recordCount/self.page.pageSize;
            }else{
                self.page.pageCount = self.page.recordCount/self.page.pageSize+1;
            }
            
            NSMutableArray *tempArr = [OrderModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"data"]];
            [ self.page.arrayData addObjectsFromArray:tempArr];
            
            
        }else{
            [self alertHUD:[data objectForKey:@"msg"]];
        }
        [self.tableView reloadData];
        if(self.page.pageCount<=self.page.pageIndex){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        if(self.page.pageIndex==1){
            [self.tableView.mj_header endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [self alertHUD:@"网络异常"];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
}

-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page.pageIndex = 1;
        [weakSelf getData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page.pageIndex ++;
        [weakSelf getData];
    }];
    
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - UITableView

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.page.arrayData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    OrderModel* orderModel = self.page.arrayData[section];
    if(orderModel.isExpansion){
        return 1;
    }else{
        return 0;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    OrderModel* orderModel = self.page.arrayData[indexPath.section];
    cell.arrayGoods = orderModel.items;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    OrderModel* orderModel =self.page.arrayData[indexPath.section];
    if(orderModel.isExpansion){
        return   orderModel.items.count*GoodsCell_H;
    }else{
        return 0;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    OrderModel* orderModel =self.page.arrayData[section];
    if(orderModel.isExpansion){
        
        return 180.f;
    }else{
        
        return 100.f;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    OrderModel* orderModel =self.page.arrayData[section];
    NSArray *deliveryArr = orderModel.delivery;
    
    if(orderModel.isExpansion){
        
        if (deliveryArr.count == 0) {
            return 250.f;
        }else{
            return 290.f;
        }
        
    }else{
        return 0.1;
    }
    
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    OrderModel* orderModel =self.page.arrayData[section];
    if(!orderModel.isExpansion){
        FinishedOrderHeaderView* header = [[FinishedOrderHeaderView alloc] init];
        [header loadData:orderModel index:section+1];
        header.delegate = self;
        header.CalPhoneBlock = ^{
            NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",orderModel.phone];
            UIWebView * callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:callWebview];
        };
        header.SummonKnightBlock = ^{

            if ([orderModel.status integerValue] == OrderStatusAlredayJieDan) {//召唤骑士
                [self summonKnightWithOrderModel:orderModel];
                
            }else if ([orderModel.status integerValue] == OrderStatusWaitInvite){//完成自取
                [self inviteWithOrderModel:orderModel];
                
            }else{//联系骑手
                OrderModel *deliveryModel = orderModel.delivery.firstObject;
                NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",deliveryModel.phone];
                UIWebView * callWebview = [[UIWebView alloc] init];
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                [self.view addSubview:callWebview];
                
            }
            
        };
        return header;
    }else{
        HandleOrderHeaderView * header = [[HandleOrderHeaderView alloc] init];
        [header loadData:orderModel index:section+1];
        header.delegate = self;
        header.CalPhoneBlock = ^{
            NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",orderModel.phone];
            UIWebView * callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:callWebview];
        };
        
        header.SummonKnightBlock = ^{

            if ([orderModel.status integerValue] == OrderStatusAlredayJieDan) {//召唤骑士
                [self summonKnightWithOrderModel:orderModel];
                
            }else if ([orderModel.status integerValue] == OrderStatusWaitInvite){//完成自取
                [self inviteWithOrderModel:orderModel];
                
            }else{//联系骑手
                OrderModel *deliveryModel = orderModel.delivery.firstObject;
                NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",deliveryModel.phone];
                UIWebView * callWebview = [[UIWebView alloc] init];
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                [self.view addSubview:callWebview];
                
            }
            
        };
        return header;
    }
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    OrderModel* empty =self.page.arrayData[section];
    if(empty.isExpansion){
        FinishedOrderFooterView* footer = [[FinishedOrderFooterView alloc] init];
        footer.delegate = self;
        footer.orderModel = self.page.arrayData[section];
        return footer;
    }else{
        return [[UIView alloc]init];
    }
    
}

-(void)inviteWithOrderModel:(OrderModel *)orderModel{
    
    [self showHUD];
    NSDictionary* arg = @{
                          @"ince":@"change_order_status",
                          @"sid":[UserHandle shareInstance].userId,
                          @"order_sn":orderModel.order_id
                          };
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        
        NSInteger flag = [[data objectForKey:@"ret"] integerValue];
        if(flag == 200){
            
            [self hidHUD:[data objectForKey:@"msg"]];
            [self refreshDataSource];
            
        }else{
            
            [self hidHUD:[data objectForKey:@"msg"]];
        }
        
    } failure:^(NSError *error) {
        [self hidHUD:@"网络异常"];
        NSLog(@"%@",error);
    }];
}

-(void)summonKnightWithOrderModel:(OrderModel *)orderModel{
    
    [self showHUD];
    NSDictionary* arg = @{
                          @"ince":@"Summon_the_knight",
                          @"sid":[UserHandle shareInstance].userId,
                          @"order_id":orderModel.order_id
                          };
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        
        NSInteger flag = [[data objectForKey:@"ret"] integerValue];
        if(flag == 200){
            
            NSString *status = [NSString stringWithFormat:@"%@",data[@"status"]];
            if ([status isEqualToString:@"1"]) {
                [self hidHUD];
                [self refreshDataSource];
            }else{
                [self hidHUD:@"召唤失败"];
            }
        }else{
            
            [self hidHUD:[data objectForKey:@"msg"]];
        }
        
    } failure:^(NSError *error) {
        [self hidHUD:@"网络异常"];
        NSLog(@"%@",error);
    }];
}

#pragma mark - OrderHeaderDelegate
-(void)handleOrderHeader:(OrderModel *)entity{
    entity.isExpansion = !entity.isExpansion;
    [self.tableView reloadData];
}
#pragma mark  HandleFooterCallDelegate
-(void)handleFooterCall:(NSString*)phoneNum{
    
    NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",phoneNum];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
    
}
#pragma mark - DZEmptyData 协议实现
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc] initWithString:@"暂无已处理订单" attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:17.0],NSForegroundColorAttributeName:[UIColor grayColor]}];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return roundf(self.tableView.frame.size.height/10.0);
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}


#pragma mark - 懒加载
-(UIView *)headerView{
    if(!_headerView){
        _headerView = [[UIView alloc]init];
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    return _headerView;
}

-(UIView *)lineView{
    
    if (!_lineView) {
        _lineView = [[UIView alloc]init];
        _lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    }
    return _lineView;
    
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.emptyDataSetSource = self;
        _tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
        _tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *))
        {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        
        [_tableView registerClass:[NewOrderTableViewCell class] forCellReuseIdentifier:self.cellIdentifier];
        [_tableView registerClass:[HandleOrderHeaderView class] forHeaderFooterViewReuseIdentifier:self.headerIdentifier];
        [_tableView registerClass:[FinishedOrderHeaderView class] forHeaderFooterViewReuseIdentifier:self.finishedHeaderIdentifier];
        [_tableView registerClass:[FinishedOrderFooterView class] forHeaderFooterViewReuseIdentifier:self.footerIdentitifer];
        
    }
    return _tableView;
}
-(Pager *)page{
    if(!_page){
        _page = [[Pager alloc]init];
        _page.pageIndex = 1;
    }
    return _page;
}

#pragma mark - 设置Button
-(void)setUpButton:(UIButton *)button withText:(NSString *)str{
    
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:button];
    [button setTitle:str forState:UIControlStateNormal];
    button.titleLabel.font =  [UIFont systemFontOfSize:11];
    button.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [button setTitleColor:[UIColor colorWithWhite:0.3 alpha:1.000] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"downarr"] forState:UIControlStateNormal];
    
    [self buttonEdgeInsets:button];
    
    UIView *verticalLine = [[UIView alloc]init];
    verticalLine.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
    [button addSubview:verticalLine];
    verticalLine.frame = CGRectMake(button.frame.size.width - 0.5, 5, 0.5, 30);
}

-(void)buttonEdgeInsets:(UIButton *)button{
    
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, -button.imageView.bounds.size.width + 2, 0, button.imageView.bounds.size.width + 10)];
    [button setImageEdgeInsets:UIEdgeInsetsMake(0, button.titleLabel.bounds.size.width + 10, 0, -button.titleLabel.bounds.size.width + 2)];
    
}

#pragma mark - 按钮点击推出菜单
-(void)clickButton:(UIButton *)button{
    
    if (button == self.statusBtn) {

        NSMutableArray *array = [NSMutableArray array];
        for (OrderModel *model in self.statusArray) {
            [array addObject:model.status_val];
        }
        [CGXPickerView showStringPickerWithTitle:@"订单类型" DataSource:array DefaultSelValue:array.firstObject IsAutoSelect:NO Manager:nil ResultBlock:^(id selectValue, id selectRow) {
            NSLog(@"%@",selectValue);
            NSLog(@"selectRow = %@",selectRow);
            NSInteger index = [selectRow integerValue];
            OrderModel *model = self.statusArray[index];
            self.statusStr = [NSString stringWithFormat:@"%@",model.status];
            
            [self.statusBtn setTitle:selectValue forState:UIControlStateNormal];
            [self buttonEdgeInsets:self.statusBtn];
            
            self.page.pageIndex = 1;
            [self getData];
        }];
        
    }else if (button == self.startBtn){
        
        
        [CGXPickerView showDatePickerWithTitle:@"时间" DateType:UIDatePickerModeDate DefaultSelValue:@"" MinDateStr:@"" MaxDateStr:@"" IsAutoSelect:NO Manager:nil ResultBlock:^(NSString *selectValue) {
            
            NSLog(@"%@",selectValue);
            
            [self.startBtn setTitle:selectValue forState:UIControlStateNormal];
            [self buttonEdgeInsets:self.startBtn];
            
            self.startStr = selectValue;
            
            self.page.pageIndex = 1;
            [self getData];
        }];
        
        
    }else{
        
        [CGXPickerView showDatePickerWithTitle:@"时间" DateType:UIDatePickerModeDate DefaultSelValue:@"" MinDateStr:@"" MaxDateStr:@"" IsAutoSelect:NO Manager:nil ResultBlock:^(NSString *selectValue) {
            
            NSLog(@"%@",selectValue);
            
            [self.endBtn setTitle:selectValue forState:UIControlStateNormal];
            [self buttonEdgeInsets:self.endBtn];
            
            self.endStr = selectValue;
            
            self.page.pageIndex = 1;
            [self getData];
            
        }];
    }
    
    
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
